package com.tang.util;

import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by win7 on 2016/1/6.
 */
public class AESUtil {

    public static String KEY = "8vNlLhwaeIwMExGaM1ou9A==";
    public static final byte[] AES_SECRET_KEY_BYTES = Base64Utils.decodeFromString(KEY);

    /**
     * AES实现加密
     *
     * @param data
     * @return
     */
    public static String aesEncrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 加密算法/工作模式/填充方式
            byte[] dataBytes = data.getBytes();
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(AES_SECRET_KEY_BYTES, "AES"));
            byte[] result = cipher.doFinal(dataBytes);
            String res = Base64Utils.encodeToString(result);
            return res;
        } catch (Exception e) {
            Log.e("TAG", "执行CodecUtil.aesEncrypt失败：data={}，异常：{}");
        }
        return "";
    }

    /**
     * AES实现解密
     *
     * @param encryptedDataBase64
     * @return
     */
    public static String aesDecrypt(String encryptedDataBase64) {
        try {
            if (!encryptedDataBase64.equals("null")) {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 加密算法/工作模式/填充方式
                byte[] dataBytes = Base64Utils.decodeFromString(encryptedDataBase64);
                cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(AES_SECRET_KEY_BYTES, "AES"));
                byte[] result = cipher.doFinal(dataBytes);
                return new String(result);
            }

        } catch (Exception e) {
            Log.e("TAG", "执行CodecUtil.aesDecrypt失败：data={}，异常：{}");
        }
        return null;
    }

}
